//
//  JYPhotoBrowserViewController.swift
//  WeiBoDemo
//
//  Created by 万佳阳 on 16/8/8.
//  Copyright © 2016年 JYWan. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

private let JYPhotoBrowserCellID = "JYPhotoBrowser"

class JYPhotoBrowserViewController: UIViewController {
    // MARK:- 定义属性
    private var indexPath : NSIndexPath
    private var picURLs : [NSURL]
    
    // MARK:- 懒加载属性
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: JYCollectionViewFlowLayout())
    private lazy var closeBtn : UIButton = UIButton(bgColor: UIColor.darkGrayColor(), fontSize: 14, title: "退 出")
    private lazy var saveBtn : UIButton = UIButton(bgColor: UIColor.darkGrayColor(), fontSize: 14, title: "保 存")
    
    // MARK:- 自定义构造函数
    init(indexPath : NSIndexPath, picURLs : [NSURL]) {
        self.indexPath = indexPath
        self.picURLs = picURLs
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:- 系统回调函数
    override func loadView() {
        super.loadView()
        view.frame.size.width += 20
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        //滚动到对应的图片
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
    }

  

}

// MARK:- 设置UI界面
extension JYPhotoBrowserViewController {
    private func setupUI() {
        //添加控件
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        //设置frame
        collectionView.frame = view.bounds
        
        closeBtn.snp_makeConstraints { (make) in
            make.leading.equalTo(20)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 90, height: 32))
        }
        
        saveBtn.snp_makeConstraints { (make) in
            make.trailing.equalTo(-20)
            make.bottom.equalTo(closeBtn.snp_bottom)
            make.size.equalTo(closeBtn.snp_size)
        }
        
        //监听按钮点击
        closeBtn .addTarget(self, action: #selector(JYPhotoBrowserViewController.closeBtnclick), forControlEvents: .TouchUpInside)
        saveBtn .addTarget(self, action: #selector(JYPhotoBrowserViewController.saveBtnclick), forControlEvents: .TouchUpInside)
        
        //设置collectionView的属性
        collectionView.registerClass(JYPhotoBrowserCell.self, forCellWithReuseIdentifier: JYPhotoBrowserCellID)
        collectionView.dataSource = self
    }
}

// MARK:- 事件监听
extension JYPhotoBrowserViewController {
    @objc private func closeBtnclick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func saveBtnclick() {
        //获取当前显示的图片
        let cell = collectionView.visibleCells().first as! JYPhotoBrowserCell
        guard let image = cell.imageView.image else {
            return
        }
        
        //将image保存到相册
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(JYPhotoBrowserViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)

    }
    
    @objc private func image(image : UIImage, didFinishSavingWithError error : NSError?, contextInfo : AnyObject) {
        var showInfo = ""
        if error != nil {
            showInfo = "保存失败"
        } else {
            showInfo = "保存成功"
        }
        SVProgressHUD.showInfoWithStatus(showInfo)
    }
}

// MARK:-collectionView数据源代理方法
extension JYPhotoBrowserViewController : UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(JYPhotoBrowserCellID, forIndexPath: indexPath) as! JYPhotoBrowserCell
        
        cell.picURL = picURLs[indexPath.item]
        cell.delegate = self
        
        return cell
        
    }
}

// MARK:- <JYPhotoBrowserCellDelegate>
extension JYPhotoBrowserViewController : JYPhotoBrowserCellDelegate {
    func imageViewClick() {
        closeBtnclick()
    }
}

// MARK:- 自定义布局
class JYCollectionViewFlowLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        //设置itemSize
        itemSize = collectionView!.bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = .Horizontal
        
        //设置collectionView的属性
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
    }
}
